package com.mail.anteater.hibernate;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.Date;

import javax.swing.Timer;

import org.apache.log4j.Logger;

import com.mail.anteater.util.StringDate;


public class Cronjob implements ActionListener{
	
	final static Logger logger = Logger.getLogger(Cronjob.class);
	
	private Timer timer = new Timer(60000, this); // 1 min timer
	
	public Cronjob(){
		timer.start();
		logger.info("Cronjob Started");
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		doRemoveTempInboxMapper();
		doRemoveTempOutboxMapper();
	}
	
	
	private void doRemoveTempInboxMapper(){
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.MINUTE, 1*-1);
		StringDate date = new StringDate(StringDate.DATE_TYPE.LONG_DATE, cal.getTime());
		String hsql = "delete from TempInboxMapper where createDt <= '" + date.toString() + "'";
		HibernateUtil.customQuery(hsql, false);
	}
	
	private void doRemoveTempOutboxMapper(){
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.MINUTE, 1*-1);
		StringDate date = new StringDate(StringDate.DATE_TYPE.LONG_DATE, cal.getTime());
		String hsql = "delete from TempOutboxMapper where createDt <= '" + date.toString() + "'";
		HibernateUtil.customQuery(hsql, false);
	}
	
	public void stop(){
		if(timer != null){
			timer.stop();
			timer = null;
		}
	}
}
